package com.sinodata.bsm.center.message;

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.log4j.Logger;

import com.sinodata.bsm.center.engine.fault.TrapDistributer;
import com.sinodata.bsm.common.message.BsmActiveMQFactory;
import com.sinodata.bsm.common.vo.FaultTrapMsg;

/**
 * 
 * <p>
 * Description: 接收trap消息
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-10 下午1:29:07          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class TrapMessageListener implements MessageListener {

    private static final Logger logger = Logger.getLogger(TrapMessageListener.class);

    private static TrapMessageListener instance = null;

    private static final String eventQueueName = "TRAP";
    private Session session;
    private Destination destination;
    private MessageConsumer consumer = null;
    private int ackMode = Session.AUTO_ACKNOWLEDGE;

    private TrapMessageListener() {
        try {
            session = BsmActiveMQFactory.getInstance().getSession(false, ackMode);
            destination = session.createQueue(eventQueueName);
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(this);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    public static synchronized void init() {
        if (instance == null) {
            if (instance == null) {
                instance = new TrapMessageListener();
            }
        }
    }

    @Override
    public void onMessage(Message message) {
        try {
            ObjectMessage objmsg = (ObjectMessage) message;
            Object msg = objmsg.getObject(); //待序列化的消息
            if (msg instanceof FaultTrapMsg) {
                FaultTrapMsg trap = (FaultTrapMsg) msg;
                TrapDistributer.getInstance().dispose(trap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
    }

}
